package jdk7;

import java.io.IOException;
import java.nio.file.*;

/**
 * 监听文件夹变化
 */
public class TestWatchService {

    private WatchService watcher;

    public TestWatchService(Path path) throws IOException{
        watcher = FileSystems.getDefault().newWatchService();
        path.register(watcher, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY});
    }

    public void handleEvents() throws InterruptedException {
        while (true){
            WatchKey key = watcher.take();
            for(WatchEvent<?> event : key.pollEvents()){
                WatchEvent.Kind kind = event.kind();
                if(kind.name().equals("OVERFLOW")){//事件可能lost or discarded
                    continue;
                }
                WatchEvent<Path> e = (WatchEvent<Path>)event;
                Path fileName = e.context();
                if(kind.name().equals("ENTRY_CREATE")){
                    System.out.println(fileName + "-----> 创建！" );
                }else if(kind.name().equals("ENTRY_DELETE")){
                    System.out.println(fileName + "-----> 删除！");
                }else if(kind.name().equals("ENTRY_MODIFY")){
                    System.out.println(fileName + "-----> 修改！");
                }
            }
            if(!key.reset()){
                break;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        String watchDir = "f:/test";
        TestWatchService watchService = new TestWatchService(Paths.get(watchDir));
        watchService.handleEvents();
    }
}
